package yolorpc.proxy;


import com.github.javafaker.Faker;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Locale;

/**
 * @author yolo
 * @Program RPC
 * @description Mock服务代理(JDK动态代理)
 * @create 2025-04-25 09:59
 **/
@Slf4j
public class MockServiceProxy implements InvocationHandler {

    private static final Faker faker = new Faker(Locale.CHINA);

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Class<?> returnType = method.getReturnType();
        log.info("mock invoke: {}", method.getName());
        return getDefaultObject(returnType);
    }

    private Object getDefaultObject(Class<?> type){
        if (type.isPrimitive()){
            if (type == boolean.class){
                return false;
            } else if (type == short.class) {
                return (short) 0;
            } else if (type == int.class) {
                return 0;
            } else if (type == long.class) {
                return 0L;
            }
        }
        // 对象类型
        try {
            if (type == String.class) {
                return faker.lorem().word();
            } else if (type == Integer.class) {
                return faker.number().randomDigit();
            } else if (type == Long.class) {
                return faker.number().randomNumber();
            } else if (type == Date.class) {
                return faker.date().birthday();
            } else if (type.isEnum()) {
                Object[] enumValues = type.getEnumConstants();
                return enumValues[faker.random().nextInt(enumValues.length)];
            }
            // 自定义对象创建
            Object instance = type.getDeclaredConstructor().newInstance();
            // TODO:使用反射填充对象字段...
            return instance;
        } catch (Exception e) {
            log.warn("mock object create failed, type: {}", type, e);
            return null;
        }
    }
}
